<template>
	<div class="header_add">
		<h1 class="add">添加</h1>
		<el-button type="primary" @click="backindex">返回</el-button>
	</div>
	<div class="tabform">
		<!-- 上传商品封面 -->
		<el-form :model="formData" :rules="rules" ref="myForm" :hide-required-asterisk='true' label-width="100px" label-position="left" class="demo-ruleForm">
			<div class="myImg">
				<el-form-item  class="imageaa">
					<label class="tuTitle">商品封面:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
					<el-upload 
						ref="upload"
						class="avatar-uploader" 
						:action="baseUrl + 'ware/uploadCover'"
						list-type="picture-card"
						:show-file-list="false" 
						:on-success="handleCoverSuccess"
						:before-upload="beforeAvatarUpload">
						<img v-if="imgUrl" :src="baseUrl+coverImg" class="avatar">
						<el-icon v-else class="el-icon-plus avatar-uploader-icon"><Plus/></el-icon>
					</el-upload>
				</el-form-item>
			</div>
		<!-- 上传商品图片 -->
		<div class="myImg">
			<el-form-item prop="files" >
				<label class="tuTitle">商品图片:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
				<el-upload
					ref="upload"
					class="avatar-uploader"
					action=""
					:auto-upload="false" 
					:file-list="wareImgList"
					:on-change="handleChange1"
					:before-upload="beforeAvatarUpload"
					list-type="picture-card" 
					:on-remove="handleRemove1">
					<el-icon class="el-icon-plus avatar-uploader-icon"><Plus/></el-icon>
				</el-upload>
			</el-form-item>
		</div>
		<!-- 上传图片详情 -->
		<div class="myImg">
			<el-form-item  prop="files" >
				<label class="tuTitle">详情图片:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
				<el-upload
					ref="upload"
					class="avatar-uploader"
					action=""
					:auto-upload="false" 
					:file-list="wareDetailsList"
					:on-change="handleChange2"
					:before-upload="beforeAvatarUpload"
					list-type="picture-card" 
					:on-remove="handleRemove2">
					<el-icon class="el-icon-plus avatar-uploader-icon"><Plus/></el-icon>
				</el-upload>
			</el-form-item>
		</div>
		<div style="display: flex; flex-wrap: wrap;">
			<el-form-item label="商品名称：" prop="wareName">
				<el-input placeholder="请填写商品名称" v-model="formData.wareName"></el-input>
			</el-form-item>
			<el-form-item label="库存量：" prop="num">
				<el-input placeholder="请填写商品库存量" v-model="formData.num"></el-input>
			</el-form-item>
			<el-form-item label="商品原价：" prop="price">
				<el-input placeholder="请填写商品原价" v-model="formData.price"></el-input>
			</el-form-item>
			<el-form-item label="会员价：" prop="vipPrice">
				<el-input placeholder="请填写商品会员价" v-model="formData.vipPrice"></el-input>
			</el-form-item>
			<el-form-item label="商品香型：" prop="flavor">
				<el-select v-model="formData.flavor" placeholder="请选择商品香型">
					<el-option v-for="flaovr in flavorlist" :label="flaovr.classifyName"
						:key="flaovr.classifyId" :value="flaovr.classifyId"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="商品类别：" prop="type">
				<el-select v-model="formData.type" placeholder="请选择商品类别">
					<el-option v-for="item in goodstypeList" :label="item.name" :value="item.id"
						:key="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="商品度数：" prop="proof">
				<el-select v-model="formData.proof" placeholder="请选择商品度数">
					<el-option v-for="proof in prooflist" :label="proof.classifyName" :value="proof.classifyId"
						:key="proof.classifyId"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="商品品牌：" prop="brand">
				<el-select v-model="formData.brand" placeholder="请选择商品品牌">
					<el-option v-for="brand in brandlist" :label="brand.classifyName" :value="brand.classifyId"
						:key="brand.classifyId"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="商品备注：" prop="wareDescr">
				<el-input placeholder="请填写商品备注" v-model="formData.wareDescr"></el-input>
			</el-form-item>
			<el-form-item v-if="updateGoodsId" label="上架操作：" prop="downStatus">
				<el-select v-model="downStatus">
					<el-option label="上架" value="1"></el-option>
					<el-option label="下架" value="0"></el-option>
				</el-select>
			</el-form-item>
		</div>
		</el-form>
	</div>
	<div class="btnadd">
		<el-button v-if="addFlag" type="primary" @click="confirmAdd(myForm)">添加</el-button>
		<el-button v-if="addFlag" @click="resetForm(myForm)">重置</el-button>
		<el-button v-if="updateFlag" type="primary" @click="confirmUpdate(myForm)">修改</el-button>
		<el-button v-if="updateFlag" @click="cancel(myForm)">取消</el-button>
	</div> 
</template>
 
<script setup lang="ts">
	// el组件
	import { ElMessage, ElMessageBox} from 'element-plus';
	import {Plus} from '@element-plus/icons-vue';
	// 接口
	import {getClassification,ListingStatus,goodsType,addGoods,uploadImg,uploadDetails,updateGoods,getGoodsById} from "../api/wqj/index"
	// ref等相关
	import { ref,reactive ,onMounted} from 'vue';
	// 路由
	import { useRouter ,useRoute} from 'vue-router';
	let router=useRouter()
	let route=useRoute()
	// 自定义
	let baseUrl="http://192.168.16.199:8081/"//基础地址用于图片显示
	let downStatus=ref("")//添加不显示上架下架
	let addFlag=ref(true)
	let updateFlag=ref(false)
	let updateGoodsId=ref<number>()//修改商品的id
	// 表单
	let formData=reactive({
		wareName: '', //商品名称，String 
		wareImg: '',//商品图片名称，String 
		wareDetails: '',//商品详情，String 
		wareDescr: '', //商品备注，String 
		brand: "", //品牌ID,int 
		flavor: '',//香型ID，int
		proof: "", //度数ID，int 
		num: "",  //库存，int 
		price: "",//原价，Bigdecmail 
		vipPrice: "",//会员价，Bigdecmail 
		type: "", //商品类型，int 
	})
	let updateformData=reactive({})
	// 验证rules
	let rules=reactive({
		wareName: [
			{ required: true, message: '请输入商品名称', trigger: 'change' },
		],
		wareDetails: [
			{ required: true, message: '请输入商品详情', trigger: 'change' }
		],
		wareDescr: [
			{ required: true, message: '请输入商品备注', trigger: 'change' }
		],
		brand: [
			{ required: true, message: '请选择品牌', trigger: 'change' }
		],
		flavor: [
			{ required: true, message: '请选择香型', trigger: 'change' }
		],
		proof: [
			{ required: true, message: '请选择度数', trigger: 'change' }
		],
		num: [
			{ validator: numInventory, trigger: 'change' }
		],
		price: [
			{ validator: numPrice, trigger: 'change' }
		],
		vipPrice: [
			{ validator: numVip, trigger: 'change' }
		],
		type: [
			{ required: true, message: '请选择度数', trigger: 'change' }
		],
	})
	let myForm=reactive(null)
	let coverImg=ref("")//商品封面
	let imgUrl=ref("")//图片显示地址
	// 商品图片多张上传
	let wareImgList=ref([])//商品图片上传的列表
	let fileList1=ref([])
	let wareImg=ref("")
	let imgAll=ref("")
	// 详情图片多张上传
	let wareDetailsList=ref([])
	let fileList2=ref([])
	let wareDetails=ref("")
	let detailImgAll=ref("")
	// 下拉框
	let flavorlist=ref([])
	let prooflist=ref([])
	let brandlist=ref([])
	let goodstypeList= [{ id: 0, name: "普通商品" }, { id: 1, name: "积分商品" }]
	// 正则表达
	var numInventory = (rule, value, callback) => {
		var reg = /^[0-9]*$/
		if (value === '') {
			callback(new Error('请输入库存量'));
		} else if (!reg.test(value)) {
			callback(new Error('只能填数字'));
		} else {
			callback();
		}
	}
	var numPrice = (rule, value, callback) => {
		var reg = /^[0-9]+\.{0,1}[0-9]{0,2}$/
		if (value === '') {
			callback(new Error('请输入价格'));
		} else if (!reg.test(value)) {
			callback(new Error('只能填数字'));
		} else {
			callback();
		}
	}
	var numVip = (rule, value, callback) => {
		var reg = /^[0-9]+\.{0,1}[0-9]{0,2}$/
		if (value === '') {
			callback(new Error('请输入库vip价格'));
		} else if (!reg.test(value)) {
			callback(new Error('只能填数字'));
		} else {
			callback();
		}
	}
	// 上传商品封面
		// 上传成功
		const handleCoverSuccess=(res, file)=>{
			// 图片名称赋值给表单中的变量
			formData.wareImg = file.response.msg
			// console.log("formData.wareImg",formData.wareImg)
			// 图片地址
			imgUrl.value = URL.createObjectURL(file.raw);
			// console.log("imgUrl.value",imgUrl.value)
			// 商品封面
			coverImg.value=res.msg
			// console.log("coverImg.value",coverImg.value)
		}
		//上传前
		const beforeAvatarUpload = (rawFile) => {
		  if (rawFile.type !== 'image/jpeg') {
		    ElMessage.error('Avatar picture must be JPG format!')
		    return false
		  } else if (rawFile.size / 1024 / 1024 > 2) {
		    ElMessage.error('Avatar picture size can not exceed 2MB!')
		    return false
		  }
		  return true
		}
	// 上传商品图片
		// 改变图片
		const handleChange1=(file, fileList)=>{
			fileList1.value=fileList
			console.log("添加时fileList1.value",fileList1.value)
		}
		// 移除图片
		const handleRemove1=(file, fileList)=>{		
			if(wareImg.value){
				var imgArr=wareImg.value.split(',');
				var result=[]
				fileList.forEach(v=>{
					result.push(v.name)
				})
				// 使用Set对象s去除result数组中的重复项
				var s=new Set(result);
				var mm=imgArr.filter(v=>s.has(v))
				wareImg.value=mm.join(",")
			}
			fileList1.value=fileList
			console.log("移除时fileList1.value",fileList1.value)
		}
	// 上传商品详情
		// 改变图片
		const handleChange2=(file, fileList)=>{
			fileList2.value=fileList
			console.log("添加时fileList2.value",fileList2.value)
		}
		// 移除图片
		const handleRemove2=(file, fileList)=>{
			if(wareDetails.value){
				var imgArr=this.wareDetails.split(',');
				var result=[]
				fileList.forEach(v=>{
					result.push(v.name)
				})
				var s=new Set(result);
				var mm=imgArr.filter(v=>s.has(v))
				wareDetails.value=mm.join(",")
			}
			fileList2.value=fileList
			console.log("移除时fileList2.value",fileList2.value)
		}
	// 下拉框数据
	// 分类接口--品牌
	const getBrand=async()=>{
		let res=await getClassification({
			classifyType:0
		})
		brandlist.value=res
		// console.log("品牌",brandlist.value)
	}
	// 分类接口--香型
	const getflavor=async()=>{
		let res=await getClassification({
			classifyType:1
		})
		flavorlist.value=res
		// console.log("香型",flavorlist.value)
	}
	// 分类接口--酒精度
	const getVol=async()=>{
		let res=await getClassification({
			classifyType:2
		})
		prooflist.value=res
		// console.log("酒精度",prooflist.value)
	}
	// 批量上传商品图片
	const uploadImgs=async()=>{
		var ImgData=new FormData()//用于接收图片
		fileList1.value.forEach(x => {
			if(x.raw){
				ImgData.append("files",x.raw);
			}
		})
		for(let [key, value] of ImgData.entries()) {  
		    // console.log("ImgData",key, value); // 这将打印出所有添加到FormData的键值对  
		}  
		let res=await uploadImg(ImgData)
		// console.log("批量上传商品图片",res)
		// 将返回结果赋值给一个字符串
		if(res.code==200){
			imgAll.value=res.data.join(',')
			if(updateGoodsId.value){//商品id存在,表示当前为修改
				wareImg.value=updateformData.wareImg+','+imgAll.value//原图片+新添加/删除	
			}else{//添加商品
				wareImg.value=imgAll.value
			}
			console.log("修改后",wareImg.value )
		}else{
			ElMessage.error(res.msg)
		}
	}
	// 批量上传详情图片
	const uploadDetailImgAll=async()=>{
		var ImgData=new FormData()//用于接收图片
		fileList2.value.forEach(x => {
			if(x.raw){
				ImgData.append("files",x.raw);
			}
		})
		let res=await uploadDetails(ImgData)
		// console.log("批量上传详情图片",res)
		if(res.code==200){
			detailImgAll.value=res.data.join(',')
			if(updateGoodsId.value){//表示当前为修改
				wareDetails.value=updateformData.wareDetails+','+detailImgAll.value//原图片+新添加/删除
			}else{//添加商品
				wareDetails.value=detailImgAll.value
			}
			console.log("修改后",wareDetails.value )
		}else{
			ElMessage.error(res.msg)
		}
	}
	
	// 添加
	const confirmAdd=async (formEL)=>{
		await uploadImgs()
		await uploadDetailImgAll()
		formEL.validate(async(valid)=>{
			if(valid){
				let res=await addGoods({
					wareName: formData.wareName,      //商品名称，String
					wareCover: coverImg.value,        //商品封面，String
					wareImg:wareImg.value,//商品图片
					wareDetails:wareDetails.value,   //商品详情，String
					wareDescr: formData.wareDescr,     //商品备注，String
					brand: formData.brand,                 //品牌ID,int
					flavor: formData.flavor,             //香型ID，int
					proof: formData.proof,             //度数ID，int
					num: formData.num,               //库存，ID
					price: formData.price,             //原价，Bigdecmail
					vipPrice: formData.vipPrice,           //vipPrice，Bigdecmail
					type: formData.type,
				})
				if(res==undefined){
					ElMessage.success('添加成功')
					setTimeout(()=>{
						router.push('/goodsManage')
					},1000)
				}
				// console.log("添加",res)
			}
		})
	}
	// 重置
	const resetForm=(myForm)=>{
		myForm.resetFields();
		imgUrl.value = ""
	}
	// 返回
	const backindex=()=>{
		router.push("/goodsManage")
	}
	// 修改
	// 根据id查询商品,并且回显数据
	const goodsInfo=async()=>{
		let res=await getGoodsById({
			wareId:updateGoodsId.value
		})
		updateformData=res[0]
		// 封面和上架情况的回显
		imgUrl.value=baseUrl + updateformData.wareCover
		coverImg.value=updateformData.wareCover
		downStatus.value=updateformData.downStatus
		// 其他数据回显 
		formData.wareName=updateformData.wareName,      //商品名称，String
		// formData.wareImg="images/ware/1723865686245.jpg",//商品图片
		// formData.wareDetails="images/ware/1723865686245.jpg",   //商品详情，String
		formData.wareDescr=updateformData.wareDescr,     //商品备注，String
		formData.brand=updateformData.brand,                 //品牌ID,int
		formData.flavor=updateformData.flavor,             //香型ID，int
		formData.proof=updateformData.proof,             //度数ID，int
		formData.num=String(updateformData.num) ,               //库存，ID
		formData.price=String(updateformData.price),             //原价，Bigdecmail
		formData.vipPrice=String(updateformData.vipPrice),           //vipPrice，Bigdecmail
		formData.type=updateformData.type,
		// 商品图片回显
		formData.wareImg=updateformData.wareImg
		var wareImg = updateformData.wareImg.split(',')
		for (var i = 0; i < wareImg.length; i++) {
			wareImg[i] = {
				"url": baseUrl + wareImg[i],
				'name':wareImg[i],
			}
		}
		wareImgList.value = [...wareImg]
		formData.wareDetails=updateformData.wareDetails
		var wareDetails = updateformData.wareDetails.split(',')
		for (var i = 0; i < wareDetails.length; i++) {
			wareDetails[i] = {
				"url":  baseUrl + wareDetails[i],
				'name':wareDetails[i],
			}
		}
		wareDetailsList.value = [...wareDetails]
		console.log("ID获取的商品信息",updateformData)
	}
	// 确认修改
	const confirmUpdate=async(formEL)=>{
		await uploadImgs()
		await uploadDetailImgAll()
		formEL.validate(async(valid)=>{
			if(valid){
				let res=await updateGoods({
					wareName: formData.wareName,      //商品名称，String
					wareCover: coverImg.value,        //商品封面，String
					wareImg:wareImg.value,//商品图片
					wareDetails:wareDetails.value,   //商品详情，String
					wareDescr: formData.wareDescr,   //商品备注，String
					brand: formData.brand,           //品牌ID,int
					flavor: formData.flavor,         //香型ID，int
					proof: formData.proof,           //度数ID，int
					num: formData.num,               //库存，ID
					price: formData.price,           //原价，Bigdecmail
					vipPrice: formData.vipPrice,     //vipPrice，Bigdecmail
					type: formData.type,
					wareId: updateGoodsId.value,
					downStatus:downStatus.value,
				})
				if(res==undefined){
					ElMessage.success('修改成功')
					setTimeout(()=>{
						router.push('/goodsManage')
					},1000)
				}
				// console.log("修改",res)
			}
		})
	}
	// 取消
	const cancel=()=>{
		imgUrl.value=baseUrl + updateformData.wareCover
		coverImg.value=updateformData.wareCover
		downStatus.value=updateformData.downStatus
		formData.wareName=updateformData.wareName,      //商品名称，String
		// formData.wareImg="images/ware/1723865686245.jpg",//商品图片
		// formData.wareDetails="images/ware/1723865686245.jpg",   //商品详情，String
		formData.wareDescr=updateformData.wareDescr,     //商品备注，String
		formData.brand=updateformData.brand,                 //品牌ID,int
		formData.flavor=updateformData.flavor,             //香型ID，int
		formData.proof=updateformData.proof,             //度数ID，int
		formData.num=String(updateformData.num) ,               //库存，ID
		formData.price=String(updateformData.price),             //原价，Bigdecmail
		formData.vipPrice=String(updateformData.vipPrice),           //vipPrice，Bigdecmail
		formData.type=updateformData.type
	}
	// 挂载
	onMounted(()=>{
		getBrand()
		getflavor()
		getVol()
		updateGoodsId.value=Number(route.query.wareId)
		if(updateGoodsId.value){//修改
			addFlag.value=false
			updateFlag.value=true
			goodsInfo()
		}else{
			addFlag.value=true
			updateFlag.value=false
		}
	})
</script>

<style lang="less">
	.header_add {
		display: flex;
		justify-content: space-between;
	}
	.tabform {
		display: flex;
		// flex-wrap: wrap;
		.el-form-item {
			margin-bottom: 24px;
			margin-right: 30px;
			width: 20vw;
			display: flex;
			align-items: center;
		}
		.myImg{	
			// width: 500px;
		
			.el-form-item {
				width: auto;
			}
			.el-form-item__content {  
			    margin-left: 0 !important; /* 使用 !important 来确保优先级 */  
			}
			.tuTitle{
				text-align: left;
				display: block;
				font-size: 14px;
				color:#606266;
				padding-left:5px;
			}
			.el-upload--picture-card {
				font-size: 28px;
				color: #8c939d;
				width: 100px;
				height: 100px;
				line-height: 100px;
				text-align: center;
			}
			.el-upload-list--picture-card .el-upload-list__item{
				width: 100px;
				height: 100px;
			}
		}
		.imageaa {
			width: 52vw;
			// object-fit: cover;
			.avatar-uploader .el-upload {
				border: 1px dashed #d9d9d9;
				border-radius: 5px;
				cursor: pointer;
				position: relative;
				overflow: hidden;
			}
			.avatar-uploader .el-upload:hover {
				border-color: #409EFF;
			}
			.avatar-uploader-icon {
				font-size: 28px;
				color: #8c939d;
				width: 100px;
				height: 100px;
				line-height: 100px;
				text-align: center;
			}
			.avatar {
				width: 100%;
				height: 100%;
				display: block;
			}
		}
	}
	.btnadd {
		width: 100%;
		display:flex;
		justify-content: center;
		margin-top: 30px;
		// .el-form-item__content {
		// 	margin-left: 0 !important;
		// }
	}
</style>